/*
 Xern Entity Relocation Network
 Copyright (C) 2011 Ronie Salgado <roniesalg@gmail.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#ifndef XERN_JSON_HPP
#define XERN_JSON_HPP

#include <string>
#include <map>
#include <vector>
#include <iostream>
#include <boost/variant/get.hpp>
#include <boost/variant/recursive_variant.hpp>
#include <boost/variant/static_visitor.hpp>
#include "Exceptions.hpp"
#include "Vector.hpp"
#include "Quaternion.hpp"

namespace Xern
{
    struct JsonObject;
    struct JsonArray;

    /**
     * JSON null. This empty structure represents a null value.
     */
    struct JsonNull
    {
    	friend std::ostream &operator<<(std::ostream &out, const JsonNull &a);
    	friend std::istream &operator>>(std::istream &in, JsonNull &a);
    };

    /**
     * JSON String.
     */
    struct JsonString
    {
    public:
        typedef std::string DataType;
        typedef DataType::iterator iterator;
        typedef DataType::const_iterator const_iterator;
        typedef DataType::value_type value_type;

        JsonString()
        {
        }

        JsonString(const JsonString &s)
			: data(s.data)
        {
        }

        JsonString(const DataType &d)
			: data(d)
        {
        }

        JsonString(const value_type *d)
			: data(d)
        {
        }

        size_t size() const
        {
        	return data.size();
        }

        value_type &operator[](int index)
        {
        	return data[index];
        }

        const value_type &operator[](int index) const
        {
        	return data[index];
        }

        iterator begin()
        {
        	return data.begin();
        }

        iterator end()
        {
        	return data.end();
        }

        const_iterator begin() const
        {
        	return data.begin();
        }

        const_iterator end() const
        {
        	return data.end();
        }

        bool operator==(const JsonString &o) const
        {
        	return data == o.data;
        }

        bool operator<(const JsonString &o) const
        {
        	return data < o.data;
        }

        JsonString &operator=(const JsonString &o)
        {
        	data = o.data;
        	return *this;
        }

        JsonString &operator=(const DataType &o)
        {
        	data = o;
        	return *this;
        }

        const value_type *c_str() const
        {
        	return data.c_str();
        }

        const DataType &string() const
        {
        	return data;
        }

        operator const DataType &() const
		{
        	return data;
		}

        friend std::ostream &operator<<(std::ostream &out, const JsonString &s);
        friend std::istream &operator>>(std::istream &in, JsonString &a);
    private:
        DataType data;
    };

    /**
     * JSON number.
     */
    typedef double JsonNumber;

    /**
     * JSON value.
     */
    typedef
        boost::variant <
			JsonNull,
			JsonString,
            JsonNumber,
            boost::recursive_wrapper<JsonObject>,
            boost::recursive_wrapper<JsonArray>
        > JsonValue;

    /**
     * JSON Object. This represents a structure.
     */
    struct JsonObject
    {
    public:
        typedef std::map<JsonString, JsonValue> DataType;
        typedef DataType::iterator iterator;
        typedef DataType::const_iterator const_iterator;
        typedef DataType::value_type value_type;

        JsonObject()
        {
        }

        JsonObject(const JsonObject &o)
            : data(o.data)
        {
        }

        JsonObject(const DataType &data)
            : data(data)
        {
        }

        size_t size() const
        {
        	return data.size();
        }

        JsonValue &operator[](const JsonString &key)
        {
        	return data[key];
        }

        const JsonValue &operator[](const JsonString &key) const
        {
        	const_iterator it = data.find(key);
        	if(it != data.end())
        		return it->second;
        	throw XernException("key not found.");
        }

        iterator begin()
        {
        	return data.begin();
        }

        iterator end()
        {
        	return data.end();
        }

        const_iterator begin() const
        {
        	return data.begin();
        }

        const_iterator end() const
        {
        	return data.end();
        }

        void clear()
        {
        	data.clear();
        }

        bool has_key(const JsonString &key) const
        {
        	return data.find(key) != data.end();
        }

        void set_key(const JsonString &key, const JsonValue &value)
        {
        	data[key] = value;
        }

        iterator find(const JsonString &key)
        {
        	return data.find(key);
        }

        const_iterator find(const JsonString &key) const
        {
        	return data.find(key);
        }

        template <typename T>
        T &get(const JsonString &key)
        {
        	return boost::get<T> (data[key]);
        }

        template <typename T>
        const T &get(const JsonString &key) const
        {
        	const_iterator it = data.find(key);
        	if(it != data.end())
        		return boost::get<T> (it->second);
        	throw XernException("key not found.");
        }

        template <typename T>
        const T &get(const JsonString &key, const T &def) const
        {
        	try
        	{
				const_iterator it = data.find(key);
				if(it != data.end())
					return boost::get<T> (it->second);
        	}
        	catch(const boost::bad_get&)
        	{
        	}

        	return def;
        }

        friend std::ostream &operator<<(std::ostream &out, const JsonObject &o);
        friend std::istream &operator>>(std::istream &in, JsonObject &a);
    private:
        DataType data;
    };

    /**
     * JSON Array. This represents an array.
     */
    struct JsonArray
    {
    public:
        typedef std::vector<JsonValue> DataType;
        typedef DataType::iterator iterator;
        typedef DataType::const_iterator const_iterator;
        typedef DataType::value_type value_type;

        JsonArray()
        {
        }

        JsonArray(const JsonArray &o)
            : data(o.data)
        {
        }

        JsonArray(const DataType &data)
            : data(data)
        {
        }

        JsonArray(const Vector3 &v)
        {
        	push_back(v.x);
        	push_back(v.y);
        	push_back(v.z);
        }

        JsonArray(const Quaternion &q)
        {
        	push_back(q.x);
        	push_back(q.y);
        	push_back(q.z);
        	push_back(q.w);
        }

        Vector3 ToVector3() const
        {
        	if(size() < 3)
        		throw XernException("Array is not a vector.");
        	return Vector3(
        			boost::get<JsonNumber> (data[0]),
        			boost::get<JsonNumber> (data[1]),
        			boost::get<JsonNumber> (data[2]));
        }

        Quaternion ToQuaternion() const
        {
        	if(size() < 4)
        		throw XernException("Array is not a quaternion.");
        	return Quaternion(
        			boost::get<JsonNumber> (data[3]),
        			boost::get<JsonNumber> (data[0]),
        			boost::get<JsonNumber> (data[1]),
        			boost::get<JsonNumber> (data[2]));
        }

        size_t size() const
        {
        	return data.size();
        }

        value_type &operator[](int index)
        {
        	return data[index];
        }

        const value_type &operator[](int index) const
        {
        	return data[index];
        }

        iterator begin()
        {
        	return data.begin();
        }

        iterator end()
        {
        	return data.end();
        }

        const_iterator begin() const
        {
        	return data.begin();
        }

        const_iterator end() const
        {
        	return data.end();
        }

        void clear()
        {
        	data.clear();
        }

        void push_back(const JsonValue &value)
        {
        	data.push_back(value);
        }

        friend std::ostream &operator<<(std::ostream &out, const JsonArray &a);
        friend std::istream &operator>>(std::istream &in, JsonArray &a);
    private:
        DataType data;
    };

	class JsonException: public XernException
	{
	public:
		JsonException(const std::string &message)
			: XernException(message) {}
	};

	inline bool JsonIsNull(const JsonValue &value)
	{
		const JsonNull *null = boost::get<JsonNull> (&value);
		return null != NULL;
	}

    std::istream &operator>>(std::istream &in, JsonValue &value);

}; // namespace Xern

#endif // XERN_JSON_HPP
